<?php
namespace app\common\model;

use think\facade\Cache;

class ConfigModel extends BaseModel
{
    protected $name = 'config';
    protected $pk='id';
    //开启自动写入时间戳
    protected $autoWriteTimestamp = false;

    /**
     * 添加配置项
     * @param $data
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addData($data) {
        if($this->where('name',$data['name'])->find()){
            exception('该配置项已存在啊！',40001);
        }
        self::create($data);
        $this->updateCache();
    }
    public function editData($data) {
        self::update($data);
        $this->updateCache();
    }

    /**
     * 删除数据
     * @param $id
     * @return bool
     */
    public function delData($id){
        $this->where('id',$id)->delete();
        $this->updateCache();
    }
    /**
     * 更新缓存
     */
    public function updateCache(){
        $config = $this->order('show_order asc')->column('value','name');
        Cache::set('webconfig',$config);
    }
    /**
     * 获取配置html
     */
    public function getListByGroupId($map){
        $list = $this->where($map)->order('show_order asc')->select();
        if($list->isEmpty()) return [];
        foreach($list as $k=>$v){
            $fun = '_'.$v['form_type'];
            $options = json_decode(html_out($v['form_config']),true);
            $valid = \FormBuild::transformationValid($v['valid']);
            if(!empty($valid)) $options['datatype']=$valid;
            $v['_html'] = \FormBuild::$fun("config[{$v['id']}][value]",$v['value'],$options);
        }
        return $list;
    }

    /**
     * 根据键获取缓存值
     */
    public function getConfig($key=null){
        $webconfig = Cache::get('webconfig');
        if(is_null($key)) return $webconfig;
        return $webconfig[$key];
    }
}